﻿Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Mvc
Imports System.Web.Mvc.Ajax
Imports VMWorkshop.Domain
Imports AutoMapper

Namespace VMWorkshop.Web.Controllers
    Public Class ProductsController
        Inherits Controller
        Private _repository As IProductRepository = Nothing

        Public Sub New(ByVal repository As IProductRepository)
            Me._repository = repository
        End Sub

        Public Sub New()
            Me.New(New ProductRepository())
        End Sub

        Public Function Index() As ActionResult
            Return List()
        End Function

        Public Function List() As ActionResult
            Dim products As IList(Of Product) = Me._repository.GetAll()

            Dim listView As IList(Of ProductListView) = Mapper.Map(Of IList(Of Product), IList(Of ProductListView))(products)

            If Request.AcceptTypes.Contains(RequestHeaders.Json) Then
                Return Json(listView)
            End If

            Return View(listView)
        End Function

        Public Function Edit(ByVal id As Integer) As ActionResult
            Dim product As Product = Me._repository.GetProductById(id)
            Dim editView As ProductEditView = ProductEditView.ToProductEditView(product)

            If Request.AcceptTypes.Contains(RequestHeaders.Json) Then
                Return Json(editView)
            End If

            Return View(editView)
        End Function

        <AcceptVerbs(HttpVerbs.Post)> _
        Public Function Persist(ByVal edit As ProductEditView) As ActionResult
            Dim newProduct As Product = ProductEditView.ToProduct(edit)
            Dim oldProduct As Product = Me._repository.GetProductById(newProduct.ProductId)

            With oldProduct
                .Title = newProduct.Title
                .Description = newProduct.Description
                .QuantityOnHand = newProduct.QuantityOnHand
                .ReleaseDate = newProduct.ReleaseDate
                .Price = newProduct.Price
            End With

            Me._repository.Persist(oldProduct)

            If Request.AcceptTypes.Contains(RequestHeaders.Json) Then
                Return Json("success")
            End If

            Return RedirectToAction("List")
        End Function

    End Class
End Namespace
